package com.jalarbee.stock.category.dao.impl;

import com.jalarbee.stock.category.business.CategoryType;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.jalarbee.core.generic.dao.DataAcessException;
import com.jalarbee.core.generic.dao.impl.GenericDaoJpa;
import com.jalarbee.stock.category.business.Category;
import com.jalarbee.stock.category.dao.CategoryDao;
import java.util.List;

@Repository(value = "categoryDao")
public class CategoryDaoJpa extends GenericDaoJpa<Category, Integer> implements CategoryDao {

    public Set<Category> getRootCategories() throws DataAcessException {
        try {
            Query rootCategoriesQuery = getEntityManager().createNamedQuery("root.categories");
            return new HashSet<Category>(rootCategoriesQuery.getResultList());
        } catch (Exception e) {
            throw new DataAcessException(e);
        }
    }

    public Set<Category> getLeafCategories() throws DataAcessException {
        try {
            Query rootCategoriesQuery = getEntityManager().createNamedQuery("leaf.categories");
            return new HashSet<Category>(rootCategoriesQuery.getResultList());
        } catch (Exception e) {
            throw new DataAcessException(e);
        }
    }

    public Set<Category> getAllCategories() throws DataAcessException {
        try {
            Query rootCategoriesQuery = getEntityManager().createNamedQuery("all.categories");
            return new HashSet<Category>(rootCategoriesQuery.getResultList());
        } catch (Exception e) {
            throw new DataAcessException(e);
        }
    }

    public Category getCategorByName(String name) {
        try {
            Query categoryByNameQuery = getEntityManager().createNamedQuery("category.by.name");
            categoryByNameQuery.setParameter("name", name);
            return (Category) categoryByNameQuery.getSingleResult();
        } catch (Exception e) {
            throw new DataAcessException(e);
        }
    }

    public List<Category> getCategoriesByType(CategoryType type) throws DataAcessException {
        try {
            Query q = getEntityManager().createQuery("from Category c where c.categoryType=:type");
            q.setParameter("type", type);
            return q.getResultList();
        } catch (Exception e) {
            throw new DataAcessException(e);
        }


    }
}
